'use strict';

const Service = require('egg').Service;
class BuildingService extends Service {
  // 新增楼栋
  async insertManyBuildings(buildings) {
    const { ctx } = this;
    const checkRes = await this.checkBuildings(buildings);
    if (checkRes.errcode) {
      return checkRes;
    }
    buildings = buildings.map(building => {
      return {
        building_num: building.building_num,
        floor: building.floor,
        desc: building.desc
      };
    });
    await ctx.model.Building.create(buildings);

    return { errcode: 0 };

  }

  async checkBuildings(buildings) {
    const errorBuildings = [];
    for (const builidng of buildings) {
      const errors = [];
      const isExist = await this.findBuildingByNumber(builidng.building_num);
      if (isExist) {
        errors.push({
          errcode: 1,
          msg: "楼栋号已存在"
        });
      }
      if (errors.length) {
        errorBuildings.push({ builidng, errors });
      }
    }
    if (errorBuildings.length) {
      return { errcode: 1, errorBuildings };
    }
    return { errcode: 0 };
  }

  // 根据楼栋号查找楼栋
  async findBuildingByNumber(number) {
    const { ctx } = this;
    const res = await ctx.model.Building.findOne({
      building_num: number * 1,
    });
    return res;
  }

  // // 更新楼栋信息
  // async updateBuildingById(id) {
  //   const { ctx } = this;
  //   const body = ctx.request.body;
  //   const newData = {
  //     building_num: body.building_num,
  //     max_floor: body.max_floor,
  //     type: body.type,
  //     can_live_count: body.can_live_count,
  //     live_count: body.live_count,
  //   };

  //   // 过滤掉undefined
  //   ctx.helper.filterUndefined(newData);

  //   return await ctx.model.Building.findByIdAndUpdate(id, newData);
  // }

  // 查找所有楼栋
  async findAllBuilding() {
    return this.ctx.model.Building.find({}).sort('building_num');
  }

  // 查询楼栋
  async searchBuildings(conditions) {
    const ctx = this.ctx;
    const page = conditions.page || 1;
    const pageSize = conditions.pageSize || 10;
    const query = {};
    if (conditions.building_num) {
      query.building_num = conditions.building_num;
    }
    if (conditions.desc) {
      query.desc = { $regex: new RegExp(conditions.desc) };
    }

    const [list, total] = await Promise.all([
      ctx.model.Building.find(query).sort('building_num').skip((page - 1) * pageSize).limit(pageSize),
      ctx.model.Building.find(query).count(),
    ]);

    return {
      list,
      paging: ctx.helper.getPaging(total, pageSize)
    };
  }
  async beforeRemoveBuilding(id) {
    const { ctx } = this;
    const errors = [];
    const isExist = await ctx.model.Building.findById(id);
    if (!isExist) {
      errors.push("该楼栋已不存在");
    }
    const count = await ctx.model.Dorm.find({ building_id: id }).count();
    if (count && isExist) {
      errors.push("该楼栋已有宿舍");
    }
    if (errors.length) {
      return { errcode: 1, errors };
    }

    return { errcode: 0 };
  }
  // 删除一个楼栋
  async removeOneBuilding(id) {
    const { ctx } = this;
    const checkRes = await this.beforeRemoveBuilding(id);
    if (checkRes.errcode) {
      return checkRes;
    }
    await ctx.model.Building.deleteOne({ _id: id });
    return { errcode: 0 };

  }

  // 修改楼栋信息
  async updateBuilding(data) {
    const { ctx } = this;
    const curBuildingExist = await ctx.model.Building.findById(data.id);
    if (!curBuildingExist) {
      return { errcode: -1, msg: "该楼栋已不存在" };
    }

    const existBuilding = await ctx.model.Building.findOne({ building_num: data.building_num });

    if (existBuilding && !(existBuilding._id.equals(data.id))) {
      return { errcode: 1, msg: "楼栋号已存在" };
    }

    await ctx.model.Building.findOneAndUpdate({ _id: data.id }, {
      building_num: data.building_num,
      floor: data.floor,
      desc: data.desc
    });

    return { errcode: 0 };
  }

}

module.exports = BuildingService;
